﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PIM.API;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

public partial class NewRecipe : System.Web.UI.Page
{
    PIMService pimService = new PIMService();
    private int _RecipeId = 0;
    private string UserIdOfRecipe = "";
    private const string pathUpload = "../Uploads/Recipes";
    private const string pathSave = "Uploads/Recipes";
    
    protected void Page_Load(object sender, EventArgs e)
    {
        
        try
        {
            if (Request.QueryString["RecipeId"] != null)
            {
                ulHead.Visible = false;
                _RecipeId = Convert.ToInt32(Request.QueryString["RecipeId"].ToString());
                if (Session["Userid"] != null)
                {
                    if (!IsPostBack)
                    {

                        GetRecipeUser(_RecipeId);
                        btnEdit.Visible = true;
                        btnUpload.Visible = false;
                        
                    }
                }
                else
                {
                    if (!IsPostBack)
                    {

                        GetRecipeUser(_RecipeId);
                    }
                }
                lnkFacebook.Visible = true;
                lnkEmail.Visible = true;
                lnkGoogle.Visible = true;
                lnkTwitter.Visible = true;
                sharefb();
            }
            else
            {
                if ((Session["Userid"] == null))
                    Response.Redirect("Default.aspx");
                ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "Rating()", true);
                btnSave.Visible = true;
                btnEdit.Visible = false;
                btnUpload.Visible = true;
                panel1.Visible = true;
                panel2.Visible = false;
                panel4.Visible = true;
                panel3.Visible = false;
                lnkFacebook.Visible = false;
                lnkEmail.Visible = false;
                lnkGoogle.Visible = false;
                lnkTwitter.Visible = false;
            }

            HtmlMeta tag = new HtmlMeta();
            tag.Attributes.Add("property", "og:title");
            tag.Content = txtRecipeName.Text;
            Page.Header.Controls.Add(tag);
            HtmlMeta tagDesc = new HtmlMeta();
            tagDesc.Attributes.Add("property", "og:description");
            tagDesc.Content = txtDescription.Text;
            Page.Header.Controls.Add(tagDesc);
            HtmlMeta tagUrl = new HtmlMeta();
            tagUrl.Attributes.Add("property", "og:url");
            tagUrl.Content = Request.Url.AbsoluteUri;
            Page.Header.Controls.Add(tagUrl);
            HtmlMeta tagImage = new HtmlMeta();
            tagImage.Attributes.Add("property", "og:image");
            tagImage.Content = hdLinkImage.Value;
            Page.Header.Controls.Add(tagImage);
            HtmlMeta tagId = new HtmlMeta();
            tagId.Attributes.Add("property", "fb:app_id");
            tagId.Content = "208238106017076";
            Page.Header.Controls.Add(tagId);
        }
        catch (Exception ex)
        {

        }
        

    }

    public void GetRecipeUser(int RecipeId)
    {
        try
        {
            RecipeUser Recipe = pimService.GetRecipeUserByRecipe(RecipeId);
            if (Recipe != null)
            {
                txtDescription.Text = Recipe.Description;
                txtRecDirection.Text = Recipe.RecDirection;
                txtRecipeName.Text = Recipe.RecipeName;
                txtIngredient.Text = Recipe.IngredientName;
                hdImage.Value = Recipe.RecipeImage;
                checkUser.Value = Recipe.UserID.ToString();
                txtServing.Text = Recipe.Serving.ToString();
                chIsPublish.Checked = Recipe.IsShared;
                Checkbox1.Checked = Recipe.IsShared;
                ratingStar.Value = Recipe.RecipeRating.ToString();
                //$(".basic1").attr('data-average', fillrating);
                //ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "error", "$('.basic1').attr('data-average','5');", true);
                ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "Rating()", true);
                if (!string.IsNullOrEmpty(Recipe.RecipeImage))
                    Image2.Src = "../" + Recipe.RecipeImage;
                hdLinkImage.Value = Common1.ResolveServerUrl(VirtualPathUtility.ToAbsolute("~/../" + Recipe.RecipeImage),false);
                lblDescription.Text = Recipe.Description;
                lblRecDirection.Text = Recipe.RecDirection.Replace(Environment.NewLine, "<br>");
                lblRecipeName.Text = Recipe.RecipeName;
                lblIngredient.Text = Recipe.IngredientName.Replace(Environment.NewLine, "<br>");
                lblServing.Text = Recipe.Serving.ToString();
                lblTime.Text = Recipe.CookTime.ToString();
                txtCook.Text = Recipe.CookTime.ToString();
            }
        }
        catch (Exception ex)
        {
        }
    }


    protected void btnInsertRecipe_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "Rating()", true);
        string nextID = pimService.GetNextID();
        try
        {
            string userId = "";

            if (Session["Userid"] != null)
                userId = Session["Userid"].ToString();

            int serving = 3;
            if (!string.IsNullOrEmpty(txtServing.Text))
                serving = Convert.ToInt32(txtServing.Text);
            int timeCook = 0;
            if (!string.IsNullOrEmpty(txtCook.Text))
                timeCook = Convert.ToInt32(txtCook.Text);
            string location = "";
            string path = "";
            if (_RecipeId == 0)
            {
                if ((fImageUpload.PostedFile != null) && (fImageUpload.PostedFile.ContentLength > 0))
                {
                    string fn = System.IO.Path.GetFileName(fImageUpload.PostedFile.FileName);
                    
                    location = Server.MapPath(pathUpload) + "/" + nextID + fn;

                    path = pathSave + "/" + nextID + fn;
                    try
                    {
                        //fImageUpload.PostedFile.SaveAs(location);
                        System.Drawing.Image image = System.Drawing.Image.FromStream(fImageUpload.PostedFile.InputStream);
                        if (image.Size.Width > 700)
                        {
                            Common1.ResizeImage(image, 700, location);
                        }
                        else
                        {
                            Common1.ResizeImage(image, image.Size.Width, location);
                        }
                    }
                    catch (Exception ex)
                    {
                        //Response.Write("Error: " + ex.Message);
                    }
                }

                string[] _Ingredient = new string[0];
                string _strIngredient = txtIngredient.Text.Replace("\r\n", "|");
                if (!string.IsNullOrEmpty(txtIngredient.Text))
                    _Ingredient = _strIngredient.Split('|');
                string a = txtIngredient.Text;
                double rating = 5;
                if (!string.IsNullOrEmpty(ratingStar.Value))
                    rating = Convert.ToDouble(ratingStar.Value);


                int result = pimService.InsertRecipe(Convert.ToInt32(userId), Convert.ToInt32(userId), 1, txtRecipeName.Text, serving, 6, timeCook, path, txtDescription.Text,
                                                rating, txtRecDirection.Text, txtIngredient.Text, Checkbox1.Checked);
                if (result > -1)
                {
                    if (_Ingredient.Count() > 0)
                    {
                        pimService.DeleteAllRecipeIngredient(result);
                        foreach (string str in _Ingredient)
                        {
                            string _rs = pimService.InsertRecipeIngredientUser(result, str, 0, 0, 0);
                        }
                    }
                    // ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Success", "alert('Insert Recipe Successful')", true);
                    Response.Redirect("MyRecipe.aspx");
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Create Recipe')", true);
                }
            }
            else
            {
                RecipeUser Recipe = pimService.GetRecipeUserByRecipe(_RecipeId);
                

                if (!string.IsNullOrEmpty(userId))
                {
                    int _idUser = Convert.ToInt32(userId);
                    int _createUserId = Convert.ToInt32(userId);

                    string[] _Ingredient = new string[0];
                    int result = -1;
                    if (_idUser == Recipe.UserID)
                    {
                        //Update Recipe Old User
                        if ((fImageUpload.PostedFile != null) && (fImageUpload.PostedFile.ContentLength > 0))
                        {
                            if (File.Exists(Server.MapPath(Recipe.RecipeImage)))
                            {
                                File.Delete(Server.MapPath(Recipe.RecipeImage));

                            }
                            string fn = System.IO.Path.GetFileName(fImageUpload.PostedFile.FileName);
                            location = Server.MapPath(pathUpload) + "/" + nextID + fn;
                            path = pathSave + "/" + nextID + fn;
                            try
                            {
                                System.Drawing.Image image = System.Drawing.Image.FromStream(fImageUpload.PostedFile.InputStream);
                                if (image.Size.Width > 700)
                                {
                                    Common1.ResizeImage(image, 700, location);
                                }
                                else
                                {
                                    Common1.ResizeImage(image, image.Size.Width, location);
                                }
                            }
                            catch (Exception ex)
                            {
                               // Response.Write("Error: " + ex.Message);
                            }
                        }
                        else
                        {
                            path = Recipe.RecipeImage;
                        }
                        string _strIngredient = txtIngredient.Text.Replace("\r\n", "|");
                        if (!string.IsNullOrEmpty(txtIngredient.Text))
                            _Ingredient = _strIngredient.Split('|');

                        string RecipeUpdate = pimService.UpdateRecipe(_RecipeId, txtRecipeName.Text, Recipe.UserID, serving, 40,
                                                timeCook, path, txtDescription.Text, Recipe.RecipeRating, txtRecDirection.Text, txtIngredient.Text, Checkbox1.Checked);
                        Image2.Src = "data:image/jpeg;charset=utf-8;base64," + hdImage.Value;
                        if (RecipeUpdate.Equals("True"))
                        {
                            if (_Ingredient.Count() > 0)
                            {
                                pimService.DeleteAllRecipeIngredient(_RecipeId);
                                foreach (string str in _Ingredient)
                                {
                                    string _rs = pimService.InsertRecipeIngredientUser(_RecipeId, str, 0, 0, 0);
                                }
                            }
                            //ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Success", "alert('Updated Recipe Successful')", true);
                            Response.Redirect("MyRecipe.aspx");
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Update a')", true);
                        }

                    }
                    else
                    {
                        /*
                         1. Kiem tra _UserId nay da co recipe do chua (bang cach check RecipeName va UserId)
                         * (if(exists(select * from RecipeUser where UserId=_UserId and RecipeName=Recipe.RecipeName)))
                         * {
                         *  update
                         * }
                         * else insert
                         */


                        RecipeUser recipeUser = pimService.GetRecipeUserByNameAndUserId(Recipe.RecipeName, _idUser);

                        if (recipeUser != null)
                        {
                            //Update Recipe
                            if ((fImageUpload.PostedFile != null) && (fImageUpload.PostedFile.ContentLength > 0))
                            {
                                if (File.Exists(Server.MapPath(Recipe.RecipeImage)))
                                {
                                    File.Delete(Server.MapPath(Recipe.RecipeImage));

                                }
                                string fn = System.IO.Path.GetFileName(fImageUpload.PostedFile.FileName);
                                location = Server.MapPath(pathUpload) + "/" + nextID + fn;
                                path = pathSave + "/" + nextID + fn;
                                try
                                {
                                    System.Drawing.Image image = System.Drawing.Image.FromStream(fImageUpload.PostedFile.InputStream);
                                    if (image.Size.Width > 700)
                                    {
                                        Common1.ResizeImage(image, 700, location);
                                    }
                                    else
                                    {
                                        Common1.ResizeImage(image, image.Size.Width, location);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //Response.Write("Error: " + ex.Message);
                                }
                            }
                            else
                            {
                                path = Recipe.RecipeImage;
                            }
                            string _strIngredient = txtIngredient.Text.Replace("\r\n", "|");
                            if (!string.IsNullOrEmpty(txtIngredient.Text))
                                _Ingredient = _strIngredient.Split('|');

                            string RecipeUpdate = pimService.UpdateRecipe(recipeUser.RecipeID, txtRecipeName.Text, recipeUser.UserID, serving, 40,
                                                    timeCook,path, txtDescription.Text, recipeUser.RecipeRating, txtRecDirection.Text, txtIngredient.Text, Checkbox1.Checked);
                            Image2.Src = "data:image/jpeg;charset=utf-8;base64," + hdImage.Value;
                            if (RecipeUpdate.Equals("True"))
                            {
                                if (_Ingredient.Count() > 0)
                                {
                                    pimService.DeleteAllRecipeIngredient(recipeUser.RecipeID);
                                    foreach (string str in _Ingredient)
                                    {
                                        string _rs = pimService.InsertRecipeIngredientUser(recipeUser.RecipeID, str, 0, 0, 0);
                                    }
                                }
                                //ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Success", "alert('Updated Recipe Successful')", true);
                                Response.Redirect("MyRecipe.aspx");
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Update')", true);
                            }


                        }
                        else
                        {
                            string _strIngredient = txtIngredient.Text.Replace("\r\n", "|");
                            if (!string.IsNullOrEmpty(txtIngredient.Text))
                                _Ingredient = _strIngredient.Split('|');
                            string a = txtIngredient.Text;
                            if ((fImageUpload.PostedFile != null) && (fImageUpload.PostedFile.ContentLength > 0))
                            {
                                string fn = System.IO.Path.GetFileName(fImageUpload.PostedFile.FileName);

                                location = Server.MapPath(pathUpload) + "/" + nextID + fn;
                                path = pathSave + "/" + nextID + fn;
                                try
                                {
                                    System.Drawing.Image image = System.Drawing.Image.FromStream(fImageUpload.PostedFile.InputStream);
                                    if (image.Size.Width > 700)
                                    {
                                        Common1.ResizeImage(image, 700, location);
                                    }
                                    else
                                    {
                                        Common1.ResizeImage(image, image.Size.Width, location);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //Response.Write("Error: " + ex.Message);
                                }
                            }
                            result = pimService.InsertRecipe(_idUser, _createUserId, 1, txtRecipeName.Text, serving, 6, timeCook, path, txtDescription.Text, 5
                                                            , txtRecDirection.Text, txtIngredient.Text, Checkbox1.Checked);
                            if (result > -1)
                            {
                                if (_Ingredient.Count() > 0)
                                {
                                    pimService.DeleteAllRecipeIngredient(result);
                                    foreach (string str in _Ingredient)
                                    {
                                        string _rs = pimService.InsertRecipeIngredientUser(result, str, 0, 0, 0);
                                    }
                                }
                                // ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Success", "alert('Insert Recipe Successful')", true);
                                Response.Redirect("MyRecipe.aspx");
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Create Recipe')", true);
                            }

                        }

                    }

                }
            }
        }
        catch (Exception ex)
        {

        }

    }

    protected void btn_Click(object sender, EventArgs e)
    {

        ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "Rating()", true);
        try
        {
            if (panel2.Visible)
            {
                btnEdit.ImageUrl = "images/btn_cancel.jpg";
                btnUpload.Visible = true;
                //GetRecipeUser(_RecipeId);
                btnSave.Visible = true;
                panel1.Visible = true;
                panel2.Visible = false;
                panel3.Visible = false;
                panel4.Visible = true;
                if (Session["Userid"].ToString() == checkUser.Value)
                {
                    btnDelete.Visible = true;
                }
            }
            else
            {
                btnEdit.ImageUrl = "images/btn_edit.jpg";
                btnUpload.Visible = false;
                btnSave.Visible = false;
                panel1.Visible = false;
                panel2.Visible = true;
                panel3.Visible = true;
                panel4.Visible = false;
                btnDelete.Visible = false;
            }
        }
        catch (Exception ex)
        {

        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        
        RecipeUser Recipe = pimService.GetRecipeUserByRecipe(_RecipeId);
        if (File.Exists(Server.MapPath("../" + Recipe.RecipeImage)))
        {
            File.Delete(Server.MapPath("../" + Recipe.RecipeImage));

        }
        bool result = Convert.ToBoolean(pimService.DeleteRecipe(_RecipeId));
        if (result)
        {
            
            Response.Redirect("MyRecipe.aspx");
        }
        else
        {
            ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "Rating()", true);
            ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Delete Recipe')", true);
        }
        //}
    }

    private void sharefb()
    {
        string url = Request.Url.AbsoluteUri;
        string facebooklink = "http://www.facebook.com/sharer.php?u=" + url;
        lnkFacebook.HRef = facebooklink;
        lnkGoogle.HRef = "https://plus.google.com/share?url=" + url;
        lnkTwitter.HRef = "https://twitter.com/intent/tweet?text=" + lblRecipeName.Text + "&url=" + url;
        lnkEmail.HRef = "mailto:?Subject=Meal Plan " + lblRecipeName.Text + "&body=Please check out recipe " + lblRecipeName.Text
            + "%0ALink: " + url;
    }

 
}